package com.mysterymall.Task;

import com.mysterymall.Common.Comp.OrderDelay;
import com.mysterymall.Common.Config.MyThreadPoolExecutor;
import com.mysterymall.Common.Utils.BaseEnum;
import com.mysterymall.Common.Utils.LogUtil;
import com.mysterymall.Mapper.OrderInfoMapper;
import com.mysterymall.Model.Entity.OrderInfo;
import com.mysterymall.Service.OrderInfoService;
import com.mysterymall.Service.PaymentService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.concurrent.DelayQueue;

@Component
public class OrderDelayQueueJob implements CommandLineRunner {
	
    // 创建一个延迟队列
	public static DelayQueue<OrderDelay> delayQueue = new DelayQueue<>();

	private final OrderInfoService orderInfoService;


	/**
	 * 构造器注入
	 * @param orderInfoService 订单服务
	 */
	public OrderDelayQueueJob(OrderInfoService orderInfoService) {
		this.orderInfoService = orderInfoService;
	}
	
	// 超过10分钟未支付订单自动关闭
	private void orderTask() {
        while (true) {
            try {
            	OrderDelay orderDelay = OrderDelayQueueJob.delayQueue.take();

				if(orderInfoService.cancelOrder(orderDelay.getOrderId())){
            		LogUtil.info("待支付订单队列剩余："+OrderDelayQueueJob.delayQueue.size()+"，订单关闭："+orderDelay.getOrderId()+"，订单创建时间："+ LocalDateTime.ofInstant(Instant.ofEpochMilli(orderDelay.getCreateTime()), ZoneId.of("GMT+8")));
            	}
            } catch (InterruptedException e) {
                break;
            }
        }
    }
 
	@Override
	public void run(String... args) throws Exception {
		// 自动取消订单开启
		LogUtil.info("自动取消订单开启");
		MyThreadPoolExecutor executor =new MyThreadPoolExecutor();
		executor.execute(this::orderTask);
	}

}